const express = require('express');
const multer = require('multer');
const path = require('path');

const router = express.Router();

// 配置multer存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../public/uploads/'));
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname);
  }
});

const upload = multer({ storage: storage });

// 单文件上传接口
router.post('/single', upload.single('file'), (req, res) => {
  const fileUrl = req.protocol + '://' + req.get('host') + '/uploads/' + req.file.filename;
  res.json({
    message: '文件上传成功',
    file: req.file,
    url: fileUrl
  });
});

// 多文件上传接口
router.post('/multiple', upload.array('files', 5), (req, res) => {
  const fileUrls = req.files.map(file => req.protocol + '://' + req.get('host') + '/uploads/' + file.filename);
  res.json({
    message: '文件上传成功',
    files: req.files,
    urls: fileUrls
  });
});

module.exports = router;